<template>
    <el-dialog
      v-model="dialogVisible"
      :destroy-on-close="true"
      :align-center="true"
      width="600px"
      title="支付项目费"
      style="padding: 20px"
    >
      <el-form
        ref="jobFormRef"
        :rules="rules"
        :model="dialogData.itemInfo"
        label-width="120px"
        label-suffix=" :"
      >
            <el-form-item label="支付总金额"  >
              <span class="total-amt-info">￥ {{ dialogData.itemInfo.totalAmt || "--" }}</span>
            </el-form-item>
            <el-form-item label="发票类型">
              <el-radio-group v-model="dialogData.itemInfo.invoiceType" @change="handleInvoiceTypeChange">
                <el-radio v-for="item in invoiceType" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="支付明细">
              <div class="payinfo-box">
                  <div class="payitem-box" v-for="(item,index) in dialogData.payItems" :key="index">
                    <div class="amt-info">￥ {{ item.payAmt }}</div>
                    <div class="note-info">{{ item.note }}</div>
                  </div>
              </div>
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select
                size="large"
                style="width: 100%"
                v-model="dialogData.itemInfo.payType"
                placeholder="支付方式"
              >
                <el-option v-for="item in PayTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button size="large" type="primary" @click="handleSubmit" :loading="btnLoading">
        确认付款
      </el-button>
      </template>
    </el-dialog>
    <OfflinePayResultDialog ref="dialogRef" />
  </template>
  <script setup lang="ts">
  import { ref, reactive } from "vue";
  import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
  import { DialogParam } from "@/biz/interface/DialogType";
  import { FlexJobPayVo } from "@/biz/interface/FlexjobType";
  import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
  import { getJobbillApi, handleJobPayApi} from "@/api/modules/cpyjob/pay"
  import { invoiceType, PayTypes} from "@/biz/datas/appData"
  import OfflinePayResultDialog from "./OfflinePayResultDialog.vue";
  import { filterEnum } from "@/utils";
  //页面的数据
  interface flexjobAbnormalDialogOption extends DialogParam {
    //弹出表单的标题
    title: string;
    // 支付明细
    payItems:[];
    //当前的数据对象
    itemInfo: FlexJobPayVo;
    //其它的数据都继续在这里加
  }
  //提交按钮，避免多次提交
  const btnLoading = ref(false);
  //弹出框的参数
  const dialogVisible = ref(false);
  //当前表单数据在这里初始化
  const dialogData = reactive<flexjobAbnormalDialogOption>({
    optType: OptEnum.UNKNOW,
    title: "",
    payItems: [],
    itemInfo: {}
  });
  
  // 接收父组件传过来的参数
  const acceptParams = (params: DialogParam): void => {
    dialogData.optType = params.optType;
    dialogData.rowData = params.rowData;
    dialogData.title = getOptTitle(dialogData.optType);
  
    if (dialogData.rowData) {
      initItemInfo();
      dialogData.itemInfo.id = dialogData.rowData.id;
      // 加载普票的支付信息
      handleInvoiceTypeChange(2);
    }
  
    dialogVisible.value = true;
  };
  
  //初始化页面的数据
  const initItemInfo = (): void => {
    dialogData.itemInfo = { invoiceType:2 };
  };
  
  // //获取当前数据的详情，直接调用接口获取数据
  // const getItemInfo = async (id: string) => {
  //   if (id) {
  //     let { data } = await getAbnormalInfoApi({ jobId:id });
  //     dialogData.itemInfo = data as unknown as AbnormalEntity;
  //   }
  // };
  
  //数据较验
  const rules = reactive({
    title: [{ required: true, message: "异议标题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "异议内容不能为空", trigger: "blur" }]
  });

  const handleInvoiceTypeChange = async (val)=>{
    let res = await getJobbillApi({
        id:dialogData.itemInfo.id,
        invoiceType:dialogData.itemInfo.invoiceType
    });
    // console.log("获取支付明细:", val, res);
    if (res.data) {
      dialogData.itemInfo.totalAmt =res.data.totalAmt;
      dialogData.payItems = res.data.items;
    }
  }

// 打开 支付
const dialogRef = ref();
const handleOpenPayDialog = (totalAmt,payNo) => {
  let params = {
    optType: OptEnum.EDIT,
    rowData: { totalAmt, payNo }
  };
  dialogRef.value.acceptParams(params);
};

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        //提交数据
        // console.log("提交的数据", dialogData.itemInfo, dynamicTags.value);
        ElMessageBox.confirm(`确认是:${filterEnum(dialogData.itemInfo.invoiceType, invoiceType)}?`, "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true
        }).then(async () => {
          let res = await handleJobPayApi({
            id:dialogData.itemInfo.id,
            invoiceType:dialogData.itemInfo.invoiceType,
            payType: dialogData.itemInfo.payType
          });
          if (res.data) {
           if(dialogData.itemInfo.payType == 4){
              ElMessage.success({ message: `支付成功！` });
              // 线下支付，跳转到提醒信息页面
              if(res.data.payNo){
                let totalAmt = res.data.totalAmt;
                let payNo = res.data.payNo;

                // 支付信息传递到信息提醒页面
                handleOpenPayDialog(totalAmt, payNo);
                // 都支持了，注这里就可以
                emits("refresh-list");
                dialogVisible.value = false;
              }
            }  else {
              ElMessage.error({message:"目前就支持线下支付."});
            }
            //刷新列表数据
            // emits("refresh-list");
            // dialogVisible.value = false;
          }
        });
        // 测试用
        // handleOpenPayDialog(13645.6, "202408301542429797");
        // dialogVisible.value = false;
      }
    } catch (error) {
      // console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

//页面事件
const emits = defineEmits(["refresh-list"]);
  //页面参数
  defineExpose({
    acceptParams
  });
</script>
<style scoped lang="scss">
.total-amt-info{
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--el-color-danger);
}

.payinfo-box{
  width: 100%;

  .payitem-box{
    // border: 1px solid red;
    margin: 10px;

    display: flex;
    align-items: center;
    justify-content: space-between;

    .amt-info{
      font-size: 1.1rem;
      font-weight: 600;
      color: var(--el-color-info);
    }

    .note-info{
      font-size: 0.75rem;
      font-weight: 400;
      color: var(--el-color-info-light-3);
    }
  }
}
</style>
  